import { Card, Form, FormInstance, Input } from 'antd';
import React, { useEffect } from 'react';

import { Info, TemplateDetailInfoBE } from '../../../../interface';
import styles from './index.module.less';

interface TemplateInfoProps {
  infoForm: FormInstance<Info>;
  templateDetail: Partial<TemplateDetailInfoBE>;
  onFormChange: (templateDetail: Partial<TemplateDetailInfoBE>) => void;
}

const TemplateInfo = ({
  infoForm,
  templateDetail,
  onFormChange
}: TemplateInfoProps): JSX.Element => {
  const handleChange = async (values: Info): Promise<void> => {
    await onFormChange({ ...templateDetail, ...values });
  };

  useEffect(() => {
    infoForm.setFieldsValue(templateDetail);
  }, [infoForm, templateDetail]);

  return (
    <Card>
      <Form form={infoForm} layout="inline" onValuesChange={handleChange}>
        <Form.Item
          required
          name="templateName"
          label="Template Name"
          className={styles['form-item']}
          validateTrigger={['onBlur', 'onChange']}
          rules={[
            {
              validator: (_, value): Promise<string | void> => {
                if (value && value.trim() !== '') {
                  return Promise.resolve();
                }
                return Promise.reject('Required');
              }
            },
            {
              max: 200,
              message: 'Max length: 200 characters'
            }
          ]}
        >
          <Input
            maxLength={200}
            style={{ width: '206px' }}
            placeholder="Enter Template Name"
          />
        </Form.Item>
      </Form>
    </Card>
  );
};

export default TemplateInfo;
